package com.alexgaoyh.echarts.test.bar;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class BarTestServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String _lastURL = (req.getRequestURL().toString().substring(req.getRequestURL().toString().lastIndexOf("/") + 1, req.getRequestURL().toString().length()));
		
		String optionJSON = generateObject(_lastURL);
		
		RequestDispatcher rd = req.getRequestDispatcher("/bar/test.jsp");
		
		req.setAttribute("optionJSON",optionJSON);//存值
		rd.forward(req,resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}

	protected void responseOutWithJson(HttpServletResponse response, String _lastURL) {  
	    //将实体对象转换为JSON Object转换  
	    response.setCharacterEncoding("UTF-8");  
	    response.setContentType("application/json; charset=utf-8");  
	    PrintWriter out = null;  
	    try {  
	        out = response.getWriter();  
	        out.append(generateObject(_lastURL));  
	    } catch (IOException e) {  
	        e.printStackTrace();  
	    } finally {  
	        if (out != null) {  
	            out.close();  
	        }  
	    }  
	}  
	
	protected String generateObject(String _lastURL) {
		
		Object result = "";
		
		try {
			Class<?> classType = Class.forName("com.alexgaoyh.echarts.test.bar.util.BarTestJSONUtil");
			
			Method generateObjectMethod = classType.getMethod("generateObject_" + _lastURL, null);
			
			result = generateObjectMethod.invoke(generateObjectMethod, null);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result.toString();
		
	}
}
